package com.fowo.api.service.handleWork;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fowo.api.entity.*;
import com.fowo.api.model.stock.in.StockInSyncWarehousingOrderAction;
import com.fowo.api.model.stock.in.StockInVo;
import com.fowo.api.model.stock.in.product.StockInProductItemVo;
import com.fowo.api.service.StockInProductService;
import com.fowo.api.service.handleWork.jindieEntity.ApiSign;
import com.fowo.api.service.handleWork.jindieEntity.addrssInfo;
import com.fowo.api.service.handleWork.jindieEntity.inStock;
import com.fowo.api.service.impl.*;
import com.fowo.api.util.LocalDateUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.*;

@Component
public class stockInSyncWarehousing implements StockInSyncWarehousingOrderAction {
    public  final static String path2="https://openapi.lingxing.com";
    public  final static String appId="ak_s4t9uVnYKwknd";
    public  final static String appSecret="xZHRMyjrRAfJkvVCoVWcxQ==";
    @Resource
    private StockInServiceImpl stockInService;
    @Resource
    protected StockInProductServiceImpl stockInProductService;

    @Resource
    private ProductServiceImpl service;
    @Resource
    private SupplierServiceImpl supplierServiceImpl;
    @Resource
    private WarehouseServiceImpl warehouseService;
    @Resource
    private ShopInfoServiceImpl shopInfoService;
    @Override
    public void run() throws Exception {
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("appId",appId);
        queryParam.put("appSecret",appSecret);
        String url=path2+"/api/auth-server/oauth/access-token";
        RestTemplate REST_TEMPLATE = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<String> httpEntity = new HttpEntity<>("", headers);
        String s= populateQueryParams(queryParam, url,false);
        ResponseEntity<Object> objectResponseEntity = REST_TEMPLATE.postForEntity(s, httpEntity, Object.class);
        MetaObject MetaObject= SystemMetaObject.forObject(objectResponseEntity.getBody());
        getAttributeList((String) MetaObject.getValue("data.access_token"));
    }


    synchronized void  getAttributeList(String access_token) throws Exception {
        String format = LocalDateUtils.format(new Date(), LocalDateUtils.DATE_PATTERN);
        RestTemplate REST_TEMPLATE = new RestTemplate();
        Map<String, Object> queryParam = new HashMap<>();
        queryParam.put("timestamp", System.currentTimeMillis() / 1000 + "");
        queryParam.put("access_token", access_token);
        queryParam.put("app_key", appId);
        queryParam.put("offset", 0);
        queryParam.put("length", 2);
        queryParam.put("search_field_time", "opt_time");//入库时间
        queryParam.put("start_date","2023-09-08");
        queryParam.put("end_date","2023-09-08");
        queryParam.put("status", 40);
        String sign = ApiSign.sign(queryParam, appId);
        queryParam.put("sign", sign);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(queryParam, requestHeaders);
        String s = populateQueryParams(queryParam, addrssInfo.path+addrssInfo.getOrders,false);
        String s2 = REST_TEMPLATE.postForObject(s, requestEntity, String.class);
        inStock supplier = JSON.parseObject(s2, inStock.class);
        if(supplier.getData()==null){
            return;
        }
        for(int i=0;i<supplier.getData().size();i++){
            inStock.DataDTO dataDTO = supplier.getData().get(i);
            StockInVo stockIn=new StockInVo();
            List<StockInProductItemVo> productList=new ArrayList<>();
            //入库类型
            if(dataDTO.getTypeText()!=null){
                if(dataDTO.getTypeText().equals("采购入库")){
                    stockIn.setReceiptType("RK002");
                }else if(dataDTO.getTypeText().equals("其他入库")){
                    stockIn.setReceiptType("RK001");
                }else if(dataDTO.getTypeText().equals("退货入库")){
                    stockIn.setReceiptType("RK003");
                }else if(dataDTO.getTypeText().equals("移除入库")){
                    stockIn.setReceiptType("RK004");
                }
            }
            stockIn.setAddType("1");//成品的
            stockIn.setProductType("1");
            StockIn one4 = stockInService.getOne(Wrappers.<StockIn>query().lambda().eq(StockIn::getOrderSn, dataDTO.getOrderSn()));
            if(one4!=null&&one4.getStatus().equals("1")){
                continue;
            }
            //获取仓库名称
            Warehouse one = warehouseService.getOne(Wrappers.<Warehouse>query().lambda().eq(Warehouse::getName, dataDTO.getWareHouseName()));
            //仓库名称
            stockIn.setWarehouse(one!=null?one.getId():null);
            stockIn.setApplicationDep((long)1);
            stockIn.setStatus("0");
            stockIn.setAStatus("0");
            stockIn.setOrderSn(dataDTO.getOrderSn());
//            stockIn.setCgUid(dataDTO.getCgUid()!=null?dataDTO.getCgUid().toString():null);
            stockIn.setCgRealname(dataDTO.getCgRealname());
            stockIn.setCreateUser((long)3);
            //设置入库日期
            stockIn.setWarehousingDate(dataDTO.getOptTime()!=null?LocalDateUtils.toDate(dataDTO.getOptTime(),LocalDateUtils.DATE_TIME_PATTERN):null);
            //设置供应商
            Supplier one1 = supplierServiceImpl.getOne(Wrappers.<Supplier>query().lambda().eq(Supplier::getSupplierName, dataDTO.getSupplierName()));
            stockIn.setSupplier(one1!=null?one1.getId():null);
            stockIn.setRemarks(dataDTO.getRemark());
            if(dataDTO.getItemList()!=null){
                for(int j=0;j<dataDTO.getItemList().size();j++){
                    inStock.DataDTO.ItemListDTO itemListDTO = dataDTO.getItemList().get(j);
                    StockInProductItemVo stockInProductItemVo=new StockInProductItemVo();
                    stockInProductItemVo.setProductPrice(!itemListDTO.getPrice().equals("-")?new BigDecimal(itemListDTO.getPrice()):null);
                    stockInProductItemVo.setRemarks(itemListDTO.getProductRemark());
                    Product one2 = service.getOne(Wrappers.<Product>query().lambda().eq(Product::getSku, itemListDTO.getSku()));
                    stockInProductItemVo.setProductId(one2!=null?one2.getId():null);
                    stockInProductItemVo.setSku(itemListDTO.getSku());
                    stockInProductItemVo.setProductName(itemListDTO.getProductName());
                    stockInProductItemVo.setQuantity(itemListDTO.getProductGoodNum());
//                    stockInProductItemVo.setFnsku(itemListDTO.getFnsku());
                    List<ShopInfo> list = shopInfoService.list(Wrappers.<ShopInfo>query().lambda().eq(ShopInfo::getShopCode, itemListDTO.getSellerId()));
                    if(list.size()>0){
                        ShopInfo one3 = list.get(0);
                        stockInProductItemVo.setShopName(one3!=null?one3.getShopName():null);
                        stockInProductItemVo.setShopId(one3!=null?Long.valueOf(one3.getId()):null);
                    }
                    stockInProductItemVo.setUnitReceiptCost(!itemListDTO.getAmount().equals("-")?new BigDecimal(itemListDTO.getAmount()):null);
                    if(one4!=null){
                        List<StockInProduct> list1 = stockInProductService.list(Wrappers.<StockInProduct>query().lambda()
                                .eq(StockInProduct::getParentStockInId, one4.getId())
                                .eq(StockInProduct::getQuantity,itemListDTO.getProductGoodNum())
                                .eq(StockInProduct::getSku, itemListDTO.getSku())
                                .eq(StockInProduct::getQuantity,itemListDTO.getProductGoodNum())
                                .eq(one2!=null, StockInProduct::getProductId,one2!=null?one2.getId():null)
                        );
                        if(list1.size()>0){
                            stockInProductItemVo.setParentStockInId(one4.getId());
                            stockInProductItemVo.setId(list1.get(0).getId());
                        }
                    }
                    productList.add(stockInProductItemVo);
                }
            }
            if(stockIn.getWarehousingDate()!=null){
                stockIn.setProductList(productList);
                if(one4!=null&&one4.getStatus().equals("0")){
                    long count = stockInProductService.count(Wrappers.<StockInProduct>query().lambda()
                            .eq(StockInProduct::getParentStockInId, one4.getId())
                            .isNotNull(StockInProduct::getUnitPrice));
                    if(count==0){
                        stockIn.setId(one4.getId());
                        stockInService.update(stockIn);
                    }
                }else{
                    if(one4==null){
                        stockInService.create(stockIn);
                    }
                }
            }
        }
    }


    static String populateQueryParams(Map<String, Object> request,String purl,boolean isEncode) {
        if(request.isEmpty()){
            return purl;
        }
        StringBuilder url = new StringBuilder(purl);
        url.append("?");
        for (Map.Entry<String, Object> entry : request.entrySet()) {
            try {
                if(isEncode){
                    url.append(URLEncoder.encode(entry.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(String.valueOf(entry.getValue()), "UTF-8"));
                }else
                {
                    url.append(entry.getKey()).append("=").append(entry.getValue());
                }
                url.append("&");
            } catch (UnsupportedEncodingException e) {
            }
        }
        if (url.charAt(url.length() - 1) == '&') {
            url.deleteCharAt(url.length() - 1);
        }
        return url.toString();
    }
}
